pagetutor.com - HTML tutorials for the rest of us

Javascript Tutor - Lesson 4

Events.

What's an event? An event is when something happens. Such as a mouse over, mouse click, page loading, etc.

We could make a simple alert box pop up when the page loads using the onLoad event handler in the body tag...

<HTML>
<HEAD>
<TITLE></TITLE>

<SCRIPT language="javascript"><!--

function HelloWorld()
{
   alert ('Hello World!');
}

//--></SCRIPT>

</HEAD>
<BODY onLoad="HelloWorld()">

Hello

</BODY>
</HTML>

Try it.

What else is there? Lots of people use onMouseOver event handlers in links. Here is the same example with a couple minor changes...

<HTML>
<HEAD>
<TITLE></TITLE>

<SCRIPT language="javascript"><!--

function HelloWorld()
{
   alert ('Hello World!');
}

//--></SCRIPT>

</HEAD>
<BODY>

<A HREF="" onMouseOver="HelloWorld()">Hello</A>

</BODY>
</HTML>

Try it.

You'll notice that the link doesn't point to anything. That's not something we'd want to leave in a finished page, but for now, since we're just learning, we'll let it slide.

We can also do an onMouseOut. The alert doesn't pop up until the mouse moves off of the link.

<HTML>
<HEAD>
<TITLE></TITLE>

<SCRIPT language="javascript"><!--

function HelloWorld()
{
   alert ('Hello World!');
}

//--></SCRIPT>

</HEAD>
<BODY>

<A HREF="" onMouseOut="HelloWorld()">Hello</A>

</BODY>
</HTML>

Try it.

Yet another event handler is onClick...

<HTML>
<HEAD>
<TITLE></TITLE>

<SCRIPT language="javascript"><!--

function HelloWorld()
{
   alert ('Hello World!');
}

//--></SCRIPT>

</HEAD>
<BODY>

<A HREF="" onClick="HelloWorld()">Hello</A>

</BODY>
</HTML>

Try it.

Exercise: Now it's your turn... make a page that asks for your name, then says Hello Yourname! when the page loads.

Here is a solution.

Can you have more than one function? Sure! You can have as many as you want. Just so you stay sane you might want to keep it as few and as organized as possible...

[SNIP]
function HelloWorld()
{
   alert ("Hello World");
}

function HelloStinky()
{
   alert ("Hello Stinky!");
}
[SNIP]

Exercise: Now, knowing this, I want you to make a web page using the three red buttons and two functions. I want the page to ask for the user's name onLoad. Then, when the mouse passes over one of the three red buttons, an alert pops up with something like "Hello Joe. You moused over number 1".

Here is a solution.

Now I suppose is a good time to explain the semicolon (;) at the end of some of the lines. The semi-colon should be used at the end of each instruction. It helps the browser know when one instruction ends and another one begins. You could also place multiple instructions on one line, separating each with a semi-colon...

instruction1;
instruction2;
instruction3;
is the same as
instruction1; instruction2; instruction3;

<< BACK         NEXT >>
pagetutor.com



Invest in the future - Hug your kid today.